package cn.com.jslh.boarpro.main.presenter;

import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;

import net.idik.lib.slimadapter.SlimAdapter;
import net.idik.lib.slimadapter.SlimAdapterEx;
import net.idik.lib.slimadapter.SlimInjector;
import net.idik.lib.slimadapter.viewinjector.IViewInjector;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.com.jslh.boarpro.R;
import cn.com.jslh.boarpro.base.BaseApplication;
import cn.com.jslh.boarpro.base.mvp.BaseListPresenter;
import cn.com.jslh.boarpro.base.mvp.BaseListView;
import cn.com.jslh.boarpro.main.model.DeliveryRecordModelImpl;
import cn.com.jslh.boarpro.main.model.breeditems.BreedItem;
import cn.com.jslh.boarpro.main.model.breeditems.ChoseBreedItem;
import cn.com.jslh.boarpro.tables.WeanTable;
import cn.com.jslh.boarpro.util.BreedingTitleUtil;
import cn.com.jslh.boarpro.util.DownLoadBaseDataUtil;
import cn.com.jslh.boarpro.util.GsonUtil;
import cn.com.jslh.boarpro.util.JSONUtil;
import cn.com.jslh.boarpro.util.WebService;
import cn.com.jslh.boarpro.util.database.DataBaseUtil;

/**
 * 分娩记录
 * 作者：周洲 on 2017/7/26 11:01
 * <p>
 * 邮箱：double0zhou@126.com
 */

public class DeliveryRecordPresenterImpl extends BaseListPresenter {
    private SlimAdapter adapter;
    private SlimAdapter uiAdapter;

    public DeliveryRecordPresenterImpl(Context context, BaseListView baseListView) {
        super(context, baseListView, new DeliveryRecordModelImpl(context));
        DownLoadBaseDataUtil.downLoadZhuSheData(context, null);//下载猪舍数据
    }

    @Override
    public void upDatas(String... param) {
        adapter.updateData(baseListModel.getDatas()).notifyDataSetChanged();
    }

    @Override
    public void setUI(RecyclerView recyclerView, String... param) {
        adapter = BreedingTitleUtil.getBreedingTitleAdapter(context, recyclerView, null, null
                , new BreedingTitleUtil.ChoseBreedItemListener() {
                    @Override
                    public void onInject(ChoseBreedItem data, IViewInjector injector) {
                        if (data.getValueid().equals("zhushe")) {
                            ((DeliveryRecordModelImpl)baseListModel).getAsyncZhuShes(new WebService.NetSuccessListener() {
                                @Override
                                public void Success(String s) throws JSONException {
                                    JSONObject jsonObject = new JSONObject(s);
                                    String flag = jsonObject.getString("flag");
                                    if(flag.equals("1")){
                                        JSONArray jsonArray = jsonObject.getJSONArray("array");
                                        final List<JSONObject> zhushes = JSONUtil.JsonArray2List(jsonArray);
                                        String[] zhusheStrs = new String[zhushes.size()];
                                        for (int i = 0; i < zhushes.size(); i++) {
                                            zhusheStrs[i] = zhushes.get(i).getString("FNAME");
                                        }
                                        new AlertDialog.Builder(context)
                                                .setTitle("选择猪舍")
                                                .setItems(zhusheStrs, new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialogInterface, final int i) {
                                                        final JSONObject zhushe = zhushes.get(i);
                                                        //进行判断
                                                        try {
                                                            ((DeliveryRecordModelImpl) baseListModel).judgeZhuShe(zhushe.getString("FID"), new WebService.NetSuccessListener() {
                                                                @Override
                                                                public void Success(String s) throws JSONException {
                                                                    JSONObject jsonObject = new JSONObject(s);
                                                                    if (jsonObject.getString("flag").equals("0")) {
                                                                        Toast.makeText(context, jsonObject.getString("warn").toString(), Toast.LENGTH_SHORT).show();
                                                                    } else {
                                                                        String values = jsonObject.getString("values");
                                                                        int index = Integer.parseInt(values.substring(0, values.indexOf(",")));
                                                                        if (index == 1 || index == 2) {
                                                                            ((BreedItem) adapter.getItem(1)).setValueStr(DeliveryRecordModelImpl.zzflktypes[index - 1]);
                                                                            DeliveryRecordModelImpl.zzFlkType = index+ "";
                                                                        }else {
                                                                            ((BreedItem) adapter.getItem(1)).setValueStr("请选择类型");
                                                                        }
                                                                        ((BreedItem) adapter.getItem(0)).setValueStr(zhushe.getString("FNAME"));
                                                                        adapter.notifyDataSetChanged();
                                                                        DeliveryRecordModelImpl.zhusheid = zhushe.getString("FID");
                                                                        upDataUI();
                                                                    }
                                                                }
                                                            });
                                                        } catch (JSONException e) {
                                                            e.printStackTrace();
                                                        }
                                                    }
                                                }).show();
                                    }

                                }
                            });
                        } else if (data.getValueid().equals("zzFlkType")) {
                            new AlertDialog.Builder(context)
                                    .setTitle("选择仔猪群类型")
                                    .setItems(DeliveryRecordModelImpl.zzflktypes, new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            ((BreedItem) adapter.getItem(1)).setValueStr(DeliveryRecordModelImpl.zzflktypes[i]);
                                            adapter.notifyDataSetChanged();
                                            DeliveryRecordModelImpl.zzFlkType = (i + 1) + "";
                                        }
                                    }).show();
                        }
                    }
                }, null);
    }

    public void setDataUI(RecyclerView recyclerView) {
        uiAdapter = SlimAdapter.create(SlimAdapterEx.class)
                .enableDiff()
                .registerDefault(R.layout.delivery_record_ui_item, new SlimInjector<JSONObject>() {
                    @Override
                    public void onInject(final JSONObject data, IViewInjector injector) {
                        try {
                            injector.text(R.id.muzhu1, data.getString("erHao"))
                                    .text(R.id.zhongmiaoshu1, data.getString("pigletQty"))
                                    .text(R.id.jianzaishu1, data.getString("jianZaiQty"))
                                    .text(R.id.ruozaishu1, data.getString("ruoZaiQty"))
                                    .text(R.id.sitaoshu1, data.getString("siTaiQty"))
                                    .text(R.id.jizaishu1, data.getString("jiZaiQty"))
                                    .text(R.id.munaiyishu1, data.getString("muNaiYiQty"))
                                    .text(R.id.wozhong1, data.getString("woWt"))
                                    .text(R.id.number, (uiAdapter.getData().size() - uiAdapter.getData().indexOf(data)) + "")
                                    .clicked(R.id.deleteImg, new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            Toast.makeText(context, "delete", Toast.LENGTH_SHORT).show();
                                            try {
                                                DataBaseUtil.excute(context, "delete from WeanTable where _id ='" + data.getString("_id") + "'");
                                                upDataUI();
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    });
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                })
                .enableEmptyView(context, R.layout.empty_layout)
                .attachTo(recyclerView);
    }

    public void upDataUI() {
        uiAdapter.updateData(((DeliveryRecordModelImpl) baseListModel).getUIDatas()).notifyDataSetChanged();
    }

    public void upActionDatas(String... params) {
//        ArrayList<Object> arrayList = DataBaseUtil.GetData(context, WeanTable.class);
//        ArrayList<Object> arrayList = DataBaseUtil.GetData(context, WeanTable.class," where zhuSheId = '"+DeliveryRecordModelImpl.zhusheid+"'");
        JSONArray jsonArray = DataBaseUtil.GetData(context,"select * from WeanTable where zhuSheId = '"+DeliveryRecordModelImpl.zhusheid+"' order by _id desc");

        if (jsonArray ==null ||jsonArray.length() == 0) {
            Toast.makeText(context, "当前无记录待上传", Toast.LENGTH_SHORT).show();
            return;
        }
        if (DeliveryRecordModelImpl.zhusheid.isEmpty()) {
            Toast.makeText(context, "请选择猪舍", Toast.LENGTH_SHORT).show();
            return;
        }
        if (DeliveryRecordModelImpl.zzFlkType.isEmpty()) {
            Toast.makeText(context, "请选择猪群类型", Toast.LENGTH_SHORT).show();
        }
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userID", SPUtils.getInstance().getString(BaseApplication.FUSERID));
            jsonObject.put("zhuSheID", DeliveryRecordModelImpl.zhusheid);
            jsonObject.put("zzFlkType", DeliveryRecordModelImpl.zzFlkType);
            jsonObject.put("entry",jsonArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ((DeliveryRecordModelImpl) baseListModel).syncUpData(jsonObject.toString(), new WebService.NetSuccessListener() {
            @Override
            public void Success(String s) throws JSONException {
                Toast.makeText(context, s.toString(), Toast.LENGTH_SHORT).show();
                if (s.contains("分娩记录提交并审核成功")) {
                    //清空数据库
                    DataBaseUtil.excute(context,"delete from WeanTable where zhuSheId = '"+DeliveryRecordModelImpl.zhusheid+"'");
                    upDataUI();
                }
            }
        });

    }
}
